package com.cyh.server.service;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.cyh.server.enums.DatabaseType;
import jakarta.annotation.Resource;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author chenyuehua
 * @description
 * @date 2025/5/27
 **/
@Service
public class DatasourceService {

    @Resource
    private DataSource dataSource;
    @Resource
    private DefaultDataSourceCreator dataSourceCreator;

    @Tool(name = "listDatasources", description = "查看所有数据库源")
    public String listDatasources() {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        return ds.getDataSources().keySet().toString();
    }

    @Tool(name = "chooseDatabase", description = "选择数据库源")
    public String chooseDatabase(@ToolParam(description = "数据库源别名") String key) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.setPrimary(key);
        return "已切换数据库源为：" + key;
    }

    @Tool(description = "创建并选择数据库源")
    public String createDatasource(@ToolParam(description = "别名") String key,
                                   @ToolParam(description = "数据库url") String url,
                                   @ToolParam(description = "数据库用户名") String username,
                                   @ToolParam(description = "数据库密码") String password,
                                   @ToolParam(description = "数据库类型") String databaseType) {
        // DatabaseType dbType = DatabaseType.getByName(databaseType);
        // if (dbType == null) {
        //     return "暂不支持的数据库类型：" + databaseType;
        // }
        // String driverClassName = dbType.getDriverClass();
        String driverClassName = "com.mysql.cj.jdbc.Driver";

        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        // 配置数据源
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setLazy(true);
        dataSourceProperty.setUsername(username);
        dataSourceProperty.setPassword(password);
        dataSourceProperty.setUrl(url);
        dataSourceProperty.setDriverClassName(driverClassName);

        // 判断数据源是否可用
        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        try (Connection connection = dataSource.getConnection()) {
            // 尝试建立连接
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 添加数据源
        ds.addDataSource(key, dataSourceCreator.createDataSource(dataSourceProperty));
        ds.setPrimary(key);

        return "已成功创建数据库连接，当前数据源：" + key;
    }
}
